package com.haiertvbic.tvnow;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.haiertvbic.tvnow.baseactivity.SwitchActivity;
import com.haiertvbic.tvnow.model.LocalCode;
import com.haiertvbic.tvnow.model.ProgramDetail;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.network.NetUtil;
import com.haiertvbic.tvnow.protocol.CAEProtocol;
import com.haiertvbic.tvnow.testblock.Function;
import com.haiertvbic.tvnow.util.Constant;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.TimeUtil;

/**
 * 跨频道搜索
 * 
 * @author sun
 * 
 */
public class AcrossChannelSearchActivity extends SwitchActivity {
	private Activity context = AcrossChannelSearchActivity.this;
	private String TAG = "AcrossChannelSearchActivity";

	private ListView programs;
	private TextView loading;
	private ProgressBar loadingBar;

	private String programId;
	private String programName;
	private String programType;
	private String js;

	private LocalCode localCode;

	// 取节目
	private Thread programThread;
	private Handler mhandler;
	private ArrayList<ProgramDetail> programList;

	private int position;
	private boolean isOutTme;

	@Override
	public void findView() {
		getProgramData();
		setContentView(R.layout.activity2_common_list);
		TextView programNameTV = (TextView) findViewById(R.id.pro_name);
		programNameTV.setText(programName);

		ImageView screenGuide = (ImageView) findViewById(R.id.screen_point_iv);
		if (Function.function.get("OttInfor")) {
			screenGuide.setImageResource(R.drawable.ott_screen_guide_3);
		} else {
			screenGuide.setImageResource(R.drawable.screen_guide_3);
		}

		programs = (ListView) findViewById(R.id.common_lv);
		loading = (TextView) findViewById(R.id.loading_tv);
		loadingBar = (ProgressBar) findViewById(R.id.bar_on_cha);

		programs.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int arg1, long id) {
				position = arg1;
				Constant.CHANNELID = Integer.valueOf(programList.get(position)
						.getCid());
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}

	@Override
	public void setDataSetup() {
		loadingBar.setVisibility(View.VISIBLE);
		loading.setVisibility(View.GONE);

		if (programThread != null) {
			programThread = null;
		}
		programThread = new Thread(new Runnable() {

			@Override
			public void run() {
				if (NetUtil.getNetworkInfo(context)) {
					// 没节目
					localCode = CAEProtocol.getLocalCode();
					String code = "1";
					if (localCode == null) {
						localCode = new LocalCode();
						code = localCode.getCity() + "";
					}
					try {
						programList = EPGWeb.getSituation(context, programId,
								code);
						if (programList != null && programList.size() > 0) {
							mhandler.sendEmptyMessage(EPGWeb.DATA_SUC);
						} else {
							mhandler.sendEmptyMessage(EPGWeb.SERVER_NO_DATA);
						}
					} catch (ClientProtocolException e) {
						mhandler.sendEmptyMessage(EPGWeb.SERVER_REQUEST_OUTIME);
					} catch (IOException e) {
						mhandler.sendEmptyMessage(EPGWeb.SERVER_REQUEST_OUTIME);
					}
				} else {
					mhandler.sendEmptyMessage(EPGWeb.NO_NETWORK);
				}
			}

		});
		programThread.start();
		if (mhandler != null) {
			return;
		}
		mhandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				loadingBar.setVisibility(View.GONE);
				switch (msg.what) {
				case EPGWeb.DATA_SUC:
					noDataShowOtt = false;
					SearchProgramAdapter adapter = new SearchProgramAdapter();
					programs.setAdapter(adapter);
					programs.requestFocus();
					programs.setVisibility(View.VISIBLE);
					loading.setVisibility(View.GONE);
					break;
				case EPGWeb.SERVER_NO_DATA:
					programs.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.server_no_data);
					break;
				case EPGWeb.SERVER_REQUEST_OUTIME:
					programs.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					String again = getString(R.string.server_request_outime);
					loading.setText(again);
					isOutTme = true;
					break;
				case EPGWeb.NO_NETWORK:
					programs.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.NOnetwork);
					break;

				default:
					break;
				}
			}
		};
	}

	private void getProgramData() {
		Intent intent = getIntent();
		programId = intent.getStringExtra("PRO_ID");
		programName = intent.getStringExtra("PRO_NAME");
		if (Function.testData.get("AcrossSearch")) {
			programName = programName.replaceAll("[0-9]", "");
			programId = "4d09e274111e1b913ef60f45fb07fca8";
			programName = "偶像独播剧场：还珠格格III";
		}

		programType = intent.getStringExtra("PRO_TYPE");

		js = intent.getStringExtra("PRO_EPISODE");
		SLog.d(TAG, "获取的PROID----》" + programId + "-----PRO_NAME" + programName);
	}

	private boolean noDataShowOtt = false;

	class SearchProgramAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return programList.size();
		}

		@Override
		public Object getItem(int position) {
			return programList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		class ViewHodler {
			// 跨频道搜索的节目
			TextView programName;
			// 该频道所在的频道名称
			TextView channel;
			// 该节目在什么时间播放
			TextView startTime;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHodler hodler = new ViewHodler();
			if (convertView == null) {
				convertView = View.inflate(context,
						R.layout.layout_across_channel_search_item, null);
				hodler.programName = (TextView) convertView
						.findViewById(R.id.program_name);
				hodler.channel = (TextView) convertView
						.findViewById(R.id.channel_name);
				hodler.startTime = (TextView) convertView
						.findViewById(R.id.start_time);
				convertView.setTag(hodler);
			} else {
				hodler = (ViewHodler) convertView.getTag();
			}
			ProgramDetail program = programList.get(position);
			hodler.programName.setText("    " + program.getPn());// 四个空格
			hodler.channel.setText("    " + program.getCname());
			String startTemp;
			if (TimeUtil.isTomorrowWeek(program)) {
				String tomorrow = getResources().getString(R.string.tomorrow);
				startTemp = tomorrow + program.getPstime() + "c";
			} else {
				startTemp = program.getPstime() + "c";
			}
			startTemp = startTemp.replace(":00c", "");
			hodler.startTime.setText(startTemp);
			return convertView;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
		case KeyEvent.KEYCODE_DPAD_LEFT:
			Intent intent = new Intent();
			if (Function.function.get("actorInfor")) {
				intent.setClass(context, ProgramActorActivity.class);
			} else {
				intent.setClass(context, ProgramListActivity.class);
			}
			startActivity(intent);
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			if (programList != null && programList.size() > 0
					&& Function.function.get("OttInfor")) {
				intent = new Intent();
				intent.setClass(context, OTTInfoActivity.class);
				intent.putExtra("PRO_NAME", programList.get(position).getPn());
				intent.putExtra("PRO_TYPE", programList.get(position)
						.getPtype());
				intent.putExtra("PRO_EPISODE", programList.get(position)
						.getJs());
				intent.putExtra("StartActivity", "AcrossChannelSearchActivity");
				startActivity(intent);
			}
			break;
		case KeyEvent.KEYCODE_ENTER:
			if (isOutTme) {
				setDataSetup();
			} else if (noDataShowOtt && Function.function.get("OttInfor")) {
				// 启动ott信息
				intent = new Intent();
				intent.setClass(context, OTTInfoActivity.class);
				intent.putExtra("PRO_NAME", programName);
				intent.putExtra("PRO_TYPE", programType);
				intent.putExtra("PRO_EPISODE", js);
				intent.putExtra("StartActivity", "ProgramListActivity");
				startActivity(intent);
			}
			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
}
